﻿#if UNITY_WX
using Core;
using UnityEngine;
using WeChatWASM;
#endif

namespace Core
{
    /// <summary>
    /// 微信小游戏
    /// </summary>
    // ReSharper disable once InconsistentNaming
    public class WXWASMFileData : Component, IAwake, IFileData
    {
#if UNITY_WX
        private WXFileSystemManager fs;
        private string ROOT = string.Empty;
        private PrefixDict prefixDict;
#endif
        public void Awake()
        {
#if UNITY_WX
            fs = WX.GetFileSystemManager();
            ROOT = $"{WX.env.USER_DATA_PATH}/";
            prefixDict = new PrefixDict(ROOT);
#endif
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();
        }

        private void CheckFile(string path, string flag)
        {
#if UNITY_WX
            var fi = new System.IO.FileInfo(path);

            var p = path[..(path.IndexOf(fi.Name) - 1)];
            var result = fs.AccessSync(p);
            //Debug.LogError($"{p} {result}");
            if (result.Equals("access:ok") == false)
            {
                fs.MkdirSync(p, true);
            }
            result = fs.AccessSync(path);
            //Debug.LogError($"{path} {result}");
            if (result.Equals("access:ok") == false)
            {
                Debug.LogError($"{path} {flag}");

                fs.OpenSync(new OpenSyncOption()
                {
                    filePath = path,
                    flag = flag
                });
            }
#endif
        }

        public string Read(string path)
        {
#if UNITY_WX
            if (fs == null) return string.Empty;

            path = prefixDict[path];

            CheckFile(path, "a+");

            var json = fs.ReadFileSync(path, "utf-8");
            if (json.StartsWith("readFileSync:fail"))
            {
                log.err($"fail msg={json}");
                return string.Empty;
            }
            return json;
#else
            return string.Empty;
#endif

        }

        public void Append(string path, string content)
        {
#if UNITY_WX
            if (fs == null) return;

            path = prefixDict[path];

            CheckFile(path, "a+");

            fs.AppendFileSync(path, content, "utf-8");
#endif
        }

        public void Write(string path, string content)
        {

#if UNITY_WX
            if (fs == null) return;

            path = prefixDict[path];

            CheckFile(path, "w");

            fs.WriteFileSync(path, content, "utf-8");
#endif
        }
        public void Delete(string path)
        {
#if UNITY_WX
            if (fs == null) return;

            path = prefixDict[path];

            //fs.
#endif
        }
    }
}
